Major differences between Array and ArrayList
An Array is a collection of similar data types that are referred to by a common name. This is useful in those situations where you are dealing with a list comprising of similar items, which can be anything like a list of cars, food items, or just about anything.
However, there are certain qualities that are unique to an Array. For instance, unlike an ArrayList, an Array is a strongly typed language. What that means is an Array can be a collection of only a specific type of elements. In contrast, an ArrayList
can have any type of items or elements.
Further, an Array can only contain data of the same data type. No such restrictions apply to the ArrayList which can be a collection of data of diverse data type. Also, an ArrayList
can accept null data types as well, something that is a strict no for an Array.
Both Array and ArrayList have different namespace as well. While Arrays belong to the System.Array
namespace, an ArrayList is part of the System.Collection
namespace.
Another important point of difference between the two is that an Array has a fixed memory size which is defined at the time of its initiation. It can’t increase or decrease during the course of program execution. An ArrayList
is a lot more flexible here in that its size can change dynamically during program execution if the program logic so demands.
Lastly, inserting and deleting an item is a lot faster in an Array compared to an ArrayList.
Here is a code snippet to demonstrate both an Array
and an ArrayList
.
Array in C#
public static void Main(string[] args) { int[] arr = new int[5]; arr[0] = 51; arr[1] = 61; arr[2] = 71; arr[3] = 81; arr[4] = 91; for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } } }
Output
51
61
71
81
91
ArrayList in C#
First, add the namespace as shown below
using System.Collections;
Now the example
public static void Main(string[] args) { ArrayList arrayList = new ArrayList(); arrayList.Add("A"); arrayList.Add("B"); arrayList.Add(1); arrayList.Add(2.5); foreach (var list in arrayList) { Console.WriteLine(list); } }
Output
A
B
1
2.5
Summary
This article discusses the basic concepts of Array and ArrayList before pointing out the key differences between the two. There is a short program as well to demonstrate both Array
and ArrayList
, complete with the output of the program to help you understand better.
Related Articles
Comments